package com.shengdong.water.code.viewmodel

import com.hjq.toast.Toaster
import com.shengdong.water.base.BaseResponse
import com.shengdong.water.base.BaseViewModel

import com.shengdong.water.code.bean.Outlet
import com.shengdong.water.code.bean.UploadBean
import com.shengdong.water.code.repository.ApiRepository
import com.shengdong.water.code.router.RouterManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import okhttp3.MultipartBody
import javax.inject.Inject


@HiltViewModel
class SignInViewModel @Inject constructor(
    private val repository: ApiRepository
) : BaseViewModel() {

    private val _outlets = MutableStateFlow<MutableList<Outlet>>(mutableListOf())
    val outlets:StateFlow<MutableList<Outlet>> = _outlets

    private val _uploadData = MutableStateFlow<UploadBean?>(null)
    val uploadData :StateFlow<UploadBean?> = _uploadData

    private val _finishActivity = MutableStateFlow(false)
    val finishActivity: StateFlow<Boolean> = _finishActivity

    fun getAllOutlets() {
        handleRequest(
            flow = repository.getAllOutlets(),
            onSuccess = { _outlets.value = it },
            onError = { code ,msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }
            },
            onToast =  {
                it
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }
    fun submitSignIn(map: MutableMap<String, Any>) {
        handleRequest(
            loading = "签到中...",
            flow = repository.submitSign(map),
            onSuccess = { it },
            onError = { code ,msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError("提交失败: $msg")
                }

            },
            onToast =  {
                // 触发关闭页面
                _finishActivity.value = true
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }

    fun upLoadFile(file: MultipartBody.Part) {
        handleRequest(
            loading = "上传中...",
            flow = repository.upLoadFile(file),
            onSuccess = { _uploadData.value = it },
            onError = {code , msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }
            },
            onToast =  {
                it
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }
}